package com.atguigu.juc.one;

//关于读写锁

import com.sun.org.apache.bcel.internal.generic.NEW;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class MyCache{
    //本地缓存 map
    private Map map = new HashMap();
    //读写锁
    private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    //put 添加，修改
    public void putData(String key,Object value){
        //加写锁
        ReentrantReadWriteLock.WriteLock writeLock =readWriteLock.writeLock();
        writeLock.lock();
        try {
            System.out.println("写操作上使用了写锁");
            map.put(key,value);
        } finally {
            writeLock.unlock();
        }

    }

    //get 查询
    public void getDatas(String key){
        //加读锁
        ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();
        readLock.lock();

        try {
            Object value = map.get(key);
            System.out.println("读操作上写了读锁：数据是"+value);
        } finally {
            readLock.unlock();
        }
    }

    //get 查询
    public void getData(String key){
        //加读锁
        ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();
        readLock.lock();

        try {
            Object value = map.get(key);
            System.out.println("读操作上写了读锁：数据是"+value);
        } finally {
            readLock.unlock();
        }
    }
}

public class ReentrantReadWriteLockDemo {

    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        for (int i = 1; i <=5 ; i++) {
            String num = String.valueOf(i);
            new Thread(()->{
                myCache.putData(num,num);
            },num).start();
        }
        for (int i = 1; i <=5 ; i++) {
            String num = String.valueOf(i);
            new Thread(()->{
                myCache.getData(num);
            },num).start();
        }
    }
}
